package com.guoheng.hazard.sys.service.impl.woZhongData;

import cn.hutool.core.collection.CollectionUtil;
import com.guoheng.hazard.common.util.StringUtils;
import com.guoheng.hazard.config.InfluxDBConfig;
import com.guoheng.hazard.sys.mapper.woZhongData.WuZhongDataMapper;
import com.guoheng.hazard.sys.model.dto.wuZhongData.*;
import com.guoheng.hazard.sys.service.impl.hazard.MonitorSensorServiceImpl;
import com.guoheng.hazard.sys.service.wuZhongData.WuZhongDataService;
import org.influxdb.InfluxDB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: cespimp-hazard-server
 * @description:
 * @author: fbl
 * @create: 2020-03-27 16:00
 **/
@Service
public class WuZhongDataServiceImpl implements WuZhongDataService {
    @Autowired
    WuZhongDataMapper wuZhongDataMapper;

    @Resource
    MonitorSensorServiceImpl monitorSensorServiceImpl;

    @Resource
    InfluxDBConfig influxDBConfig;


    @Resource
    InfluxDB influxDB;

    @Override
    public WoZhongTankDataDTO getTankSensorData(String tankId, String companyId) throws Exception {
        // 截取tankId小数点后的数字
        String newTankId = delPoint(tankId);
        String newCompanyId = delPoint(companyId);
        // 储罐企业信息
        WoZhongTankDataDTO tankSensorData = wuZhongDataMapper.getTankSensorData(newTankId, newCompanyId);

        List<Date> reportData = new ArrayList<>();

        // 传感器基本信息
        List<TankSensorDataDTO> monitorSensor = wuZhongDataMapper.getMonitorSensor(tankSensorData.getTankId());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 查询传感器最新的值
        for (TankSensorDataDTO tankSensorDataDTO : monitorSensor) {
            String sensorId = tankSensorDataDTO.getSensorId();
            // 查询传感器数据(influxDB数据库数据)
            String sql = "select sensorValue,time from " + influxDBConfig.getMeasurement() + " where  sensorId = "+ "'" + sensorId + "' order by time desc limit 1 tz('Asia/Shanghai')";
            List<Map> sensorValue = monitorSensorServiceImpl.query(influxDB, sql, Map.class);

            // 查询传感器的最新数据信息
            // HashMap<String, Object> sensorValue = wuZhongDataMapper.getSensorValue(sensorId);

            if (sensorValue != null) {
                tankSensorDataDTO.setSensorValue(String.valueOf(sensorValue.get(0).get("sensorValue")));
                Date time = new Date(Long.valueOf(sensorValue.get(0).get("time") + ""));
                reportData.add(time);
                // 设置传感器报警状态
                Integer alarmStatue = setAlarmStatue(tankSensorDataDTO, Double.parseDouble(sensorValue.get(0).get("sensorValue") + ""));
                tankSensorDataDTO.setSensorFlag(alarmStatue);
            }
        }
        tankSensorData.setEntries(monitorSensor);
        // 传感器最新时间
        if(CollectionUtil.isNotEmpty(reportData)){
            tankSensorData.setMonitorTime(format.format(Collections.max(reportData)));
        }
        return tankSensorData;
    }

    @Override
    public WoZhongTankHistoryDataDTO getSensorHistoryData(String beginTime, String endTime, String sensorId, String tankId, String companyId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 重置开始和结束时间
        if (StringUtils.isEmpty(beginTime) || StringUtils.isEmpty(endTime) ) {
            Calendar ca = Calendar.getInstance();
            ca.setTime(new Date());
            // 前一天的当前时间
            ca.add(Calendar.DATE, -1);
            Date yesterday = ca.getTime();
            beginTime = format.format(yesterday);
            endTime = format.format(new Date());
        }

        // 查询企业和储罐的基本信息
        WoZhongTankHistoryDataDTO tankHistoryData = wuZhongDataMapper.getTankHistoryData(sensorId, tankId, companyId);

        if (tankHistoryData == null) {
            return null;
        }
        // 储罐下的传感器基本信息
        List<TankSensorHistoryDataDTO> monitorHistorySensor = wuZhongDataMapper.getMonitorHistorySensor(tankHistoryData.getTankId(), sensorId);
        ArrayList<Long> monitorTime = new ArrayList<>();

        for (TankSensorHistoryDataDTO tankSensorDataDTO : monitorHistorySensor) {
            String sId = tankSensorDataDTO.getSensorId();
            // 查询传感器数据(influxDB数据库数据)
            String sql = "select sensorValue,time from " + influxDBConfig.getMeasurement() + " where time < " + "'" + endTime + "' and time >" + "'" + beginTime + "'";
            if (sId != null) {
                sql += "and sensorId = " + "'" + sId + "'";
            }
            // influxDB时区
            sql += " tz('Asia/Shanghai')";
            List<Map> query = monitorSensorServiceImpl.query(influxDB, sql, Map.class);
            ArrayList<String> sensorValue = new ArrayList<>();
            for (Map map : query) {
                sensorValue.add(map.get("sensorValue") + "");
                String time = map.get("time") + "";
                if(time.contains("E")){
                    BigDecimal bigDecimal = new BigDecimal(time);
                    monitorTime.add(Long.valueOf(bigDecimal.toPlainString()));
                }else{
                    monitorTime.add(Long.valueOf(time));
                }
            }
            // 置入历史数据信息
            tankSensorDataDTO.setData(sensorValue);
        }
        // 置入监测时间
        if (CollectionUtil.isNotEmpty(monitorTime)) {
            tankHistoryData.setMonitorTime(Collections.max(monitorTime));
        }

        // 置入传感器信息
        tankHistoryData.setDatas(monitorHistorySensor);
        tankHistoryData.setTimes(monitorTime);

        return tankHistoryData;
    }

    @Override
    public HashMap<String, Object> getSensorAlarmData(String sensorId, String tankId, String companyId) {

        // 报警的基本信息
        List<WoZhongSensorAlarmDTO> sensorAlarmData = wuZhongDataMapper.getSensorAlarmData(sensorId, tankId, companyId);
        // 去除所有集合为null的元素
        sensorAlarmData.removeAll(Collections.singleton(null));
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        if (CollectionUtil.isEmpty(sensorAlarmData)) {
            stringObjectHashMap.put("entries", new ArrayList<String>());
        } else {
            stringObjectHashMap.put("entries", sensorAlarmData);
        }
        return stringObjectHashMap;
    }

    @Override
    public HashMap<String, Object> getSensorHistoryAlarmData(String companyCode, String beginTime, String endTime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        if (StringUtils.isEmpty(beginTime)   || StringUtils.isEmpty(endTime)) {
            cal.setTime(new Date());
            // 获得当前日期是一个星期的第几天
            int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
            if (1 == dayWeek) {
                cal.add(Calendar.DAY_OF_MONTH, -1);
            }
            // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            // 获得当前日期是一个星期的第几天
            int day = cal.get(Calendar.DAY_OF_WEEK);
            // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
            cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);

            endTime = format.format(new Date());
            beginTime = format.format(cal.getTime());
        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        List<WoZhongHistoryAlarmDTO> sensorHistoryAlarmData = wuZhongDataMapper.getSensorHistoryAlarmData(companyCode, beginTime, endTime);

        // 去除所有集合为null的元素
        sensorHistoryAlarmData.removeAll(Collections.singleton(null));
        if (CollectionUtil.isEmpty(sensorHistoryAlarmData)) {
            stringObjectHashMap.put("entries", new ArrayList<String>());
        } else {
            stringObjectHashMap.put("entries", sensorHistoryAlarmData);
        }
        return stringObjectHashMap;
    }

    // 去除小数点
    private String delPoint(String arg) {
        if (arg != null && !arg.equals("") && arg.contains(".")) {
            int indexOf = arg.lastIndexOf(".");
            return arg = arg.substring(0, indexOf);
        }
        return arg;
    }

    // 设置报警状态
    private Integer setAlarmStatue(TankSensorDataDTO sensorDataDTO, Double sensorValue) {

        if (sensorDataDTO.getFirstAlarmThreshold() != null && sensorValue < sensorDataDTO.getFirstAlarmThreshold()) {
            return 1;
        } else {
            if (sensorDataDTO.getSecondAlarmThreshold() != null && sensorValue < sensorDataDTO.getSecondAlarmThreshold()) {
                return 2;
            }
        }
        if (sensorDataDTO.getThirdAlarmThreshold() != null && sensorValue > sensorDataDTO.getThirdAlarmThreshold()) {
            return 3;
        } else {
            if (sensorDataDTO.getFourthAlarmThreshold() != null && sensorValue > sensorDataDTO.getFourthAlarmThreshold()) {
                return 4;
            }
        }
        return 0;
    }
}
